<template>
  <div class="app-container">
    <el-tabs v-model="queryParams.status" type="card" @tab-click="handleClickStatus">
      <el-tab-pane name="-1">
        <span slot="label"><i class="el-icon-s-order"></i> 全部任务</span>
      </el-tab-pane>
      <el-tab-pane name="1">
        <span slot="label"><i class="el-icon-refrigerator"></i> 进行中</span>
      </el-tab-pane>
      <el-tab-pane name="3">
        <span slot="label"><i class="el-icon-circle-check"></i> 已完成</span>
      </el-tab-pane>
      <el-tab-pane name="2">
        <span slot="label"><i class="el-icon-circle-close"></i> 已撤回</span>
      </el-tab-pane>
    </el-tabs>

    <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="业务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择业务状态" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="完成时间" prop="finishTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.finishTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择完成时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['task:workflow:edit']"
          >修改</el-button
        >
      </el-col>


    </el-row> -->

    <el-table
      v-loading="loading"
      :data="workflowList"
      @selection-change="handleSelectionChange"
      class="workflow-list"
      :row-class-name="rowClass"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务" align="center" prop="taskName" sortable />
      <el-table-column label="归属企业" align="center" prop="deptName" />
      <el-table-column label="任务类型" align="center" prop="taskStatus">
        <template v-slot="{ row }">
          <div>{{ formatTaskStatus(row) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template v-slot="{ row }">
          <div>{{ formatStatus(row) }}</div>
          <div>{{ formatReason(row) }}</div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="visible">
        <template v-slot="{ row }">{{ row.visible ? '是' : '否' }}</template>
      </el-table-column> -->

      <el-table-column label="任务执行人" align="center" prop="doUser" />
      <el-table-column label="时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.startTime }}</div>
          <div>{{ formatTime(scope.row) }}</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['task:workflow:list']"
            >查看任务</el-button
          >

          <template v-if="scope.row.status == 1">
            <template v-if="scope.row.doUser == name">
              <el-button size="mini" type="text" icon="el-icon-check" @click="handleFinish(scope.row)">{{
                isCheck(scope.row.taskStatus) ? '通过' : '完成'
              }}</el-button>
              <el-button
                v-if="isCheck(scope.row.taskStatus)"
                size="mini"
                type="text"
                icon="el-icon-close"
                @click="handleReject(scope.row)"
                >不通过</el-button
              >
            </template>

            <el-button
              v-if="scope.row.status == 1"
              size="mini"
              type="text"
              icon="el-icon-d-arrow-left"
              @click="handleRevoke(scope.row)"
              v-hasPermi="['task:workflow:revoke']"
              >撤回</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务流程控制对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="ID" prop="id">
          <el-input v-model="form.id" placeholder="请输入ID" />
        </el-form-item>
        <el-form-item label="归属企业id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入归属企业id" />
        </el-form-item>
        <el-form-item label="业务状态">
          <el-radio-group v-model="form.taskStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="撤回原因" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入撤回原因" />
        </el-form-item>
        <el-form-item label="任务执行人" prop="doUser">
          <el-input v-model="form.doUser" placeholder="请输入任务执行人" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.finishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择完成时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@/assets/styles/workflow.scss'
import { mapGetters } from 'vuex'

import { checkRole, checkPermi } from '@/utils/permission'
import { formatTaskStatus, formatStatus, formatReason, formatTime, getStep } from '@/utils/workflow'

import {
  listWorkflow,
  getWorkflow,
  assignTask,
  pickTask,
  finishTask,
  rejectTask,
  revokeTask,
  updateWorkflow,
  exportWorkflow,
} from '@/api/task/workflow'

import EList from '@/views/task/components/EList'

export default {
  name: 'Workflow',
  components: { EList },
  computed: {
    ...mapGetters(['name']),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 任务流程控制表格数据
      workflowList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        taskStatus: undefined,
        status: '-1',
        reason: undefined,
        doUser: undefined,
        startTime: undefined,
        finishTime: undefined,
        visible: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
        taskStatus: [{ required: true, message: '业务状态不能为空', trigger: 'blur' }],
      },

      // dialog
      userSelectVisible: false,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermi,
    /** 查询任务流程控制列表 */
    getList() {
      this.loading = true
      const { status, ...queryParams } = this.queryParams
      if (status != '-1') {
        queryParams.status = status
      }
      listWorkflow(queryParams).then((response) => {
        this.workflowList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleClickStatus(tab, event) {
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        taskId: undefined,
        deptId: undefined,
        taskStatus: '0',
        // status: '0',
        reason: undefined,
        doUser: undefined,
        startTime: undefined,
        finishTime: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.taskId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    // 查看标注任务 /mark/qatask?taskId=7770
    handleView(row) {
      this.$router.push({ path: '/mark/task', query: { taskId: row.taskId } })
    },

    handleFinish(workflow) {
      this.submitWorkflow(finishTask, workflow.id, '更新成功!')
    },
    handleReject(workflow) {
      this.submitWorkflow(rejectTask, workflow.id, '更新成功!')
    },
    handleRevoke(workflow) {
      this.submitWorkflow(revokeTask, workflow.id, '撤回成功!')
    },

    submitWorkflow(func, data, msg) {
      func(data)
        .then((res) => {
          if (res.code === 200) {
            this.msgSuccess(msg)
            this.getList()
          } else {
            this.msgError(res.msg)
          }
        })
        .catch((err) => {
          this.msgError(err.msg)
        })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const taskId = row.taskId || this.ids
      getWorkflow(taskId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改任务流程控制'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.taskId != undefined) {
            updateWorkflow(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有任务?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportWorkflow(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
        })
        .catch(function () {})
    },

    /**
     * 样式
     */
    rowClass({ row }) {
      if (row.status === 3) {
        return ['finish', 'reject'][row.reason - 1]
      }
      return ['waiting', 'doing', 'revoke'][row.status]
    },

    /**
     * 格式化
     */
    formatTaskStatus,
    formatStatus,
    formatReason,
    formatTime,
    isCheck(status) {
      return getStep(status) > 2
    },
  },

  filters: {},
}
</script>
